package com.ft.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ft.dao.MoneyDao;
import com.ft.dao.NongsukeOrderDao;
import com.ft.dao.NongsukeallidDao;
import com.ft.dao.UserDao;
import com.ft.domain.*;
import com.ft.service.INongsukeallidService;
import com.ft.utils.ObjectUtils;
import com.ft.websocket.service.ChatEndpoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class NongsukeallidServiceImpl extends ServiceImpl<NongsukeallidDao, Nongsukeallid> implements INongsukeallidService {

    @Autowired
    private NongsukeallidDao nongsukeallidDao;
    @Autowired
    private NongsukeOrderDao nongsukeOrder;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserDao userDao;
    @Autowired
    private MoneyDao moneyDao;
    /**
     * 增加总表
     *
     * @param order
     * @return
     * @throws IllegalAccessException
     */
    @Override
    public int addOrder(Nongsukeallid order) throws IllegalAccessException {
        //处理数据
        ArrayList<NongsukeOrder> jsonContents = new ArrayList<>();
        JSONArray orders = JSON.parseArray(order.getOrderlist());
        for (Object jsonObject : orders) {
            NongsukeOrder jsonContent = JSONObject.parseObject(jsonObject.toString(), NongsukeOrder.class);
            jsonContents.add(jsonContent);
        }
        //先创建助农服务订单内容表
        for (NongsukeOrder o : jsonContents) {
            o.setBelongid(String.valueOf(order.getId()));
            System.out.println(o.toString());
            int j = nongsukeOrder.addOrder(o);
            if (j == 0) {
                return 0;
            }
        }
        String orderlist = JSON.toJSONString(jsonContents);
        order.setOrderlist(orderlist);
        //在创建助农服务订单表
        int i = nongsukeallidDao.addOrder(order);
        if (i == 1) {
            //将id放到助农服务的所有订单zset中
            Long oldBuyOrderId = redisTemplate.opsForZSet().zCard("nongsukeallId");
            redisTemplate.opsForZSet().add("nongsukeallId", ""+order.getId(), 0);
            //2.将订单号存入用户的未付款的set里
            int userid = order.getIssueid();
            //将订单号放入我创建的的助农服务商品中
            String key2 = userid + ":buynongsukegoods";
            redisTemplate.boundSetOps(key2).add(order.getId());
            //3.将订单数据存入hash
            String orderKey1 = "nongsukeall:" + order.getId();
            Map<String, Object> stringObjectMap = ObjectUtils.objectToMap(order);
            redisTemplate.opsForHash().putAll(orderKey1, stringObjectMap);
            //4.更新时间
            String time = nongsukeallidDao.getcreateTime(order.getId());
            order.setCreateTime(Timestamp.valueOf(time));
            redisTemplate.opsForHash().put(orderKey1, "createTime", time);
            return 1;
        }
        return 0;
    }

    /**
     * 更加订单id获取订单数据
     *
     * @param id
     * @return
     */
    @Override
    public Nongsukeallid getOrder(Long id) {
        Nongsukeallid nongsukeallid = nongsukeallidDao.selectOrder(id);
        return nongsukeallid;
    }

    /**
     * 查询用于支付的信息
     *
     * @param id 订单id
     * @return
     */
    @Override
    public Nongsukeallid selectOrderToPay(Long id) {
        Nongsukeallid nongsukeallid = nongsukeallidDao.selectOrderToPay(id);
        return nongsukeallid;
    }

    /**
     * 用户购买付款后更新订单状态
     *
     * @param userid
     * @param id
     * @return
     */
    @Override
    public int updataOrderState(String id, int userid) {
        int i = nongsukeallidDao.updataOrderState(id);
        String key = "nongsukeall:" + id;
        if (i == 1) {
            //将订单类型zet集合中的对应订单id的score值加1
            redisTemplate.opsForZSet().incrementScore("nongsukeallId", id, 1);
            //修改订单hash表state状态
            redisTemplate.opsForHash().put(key, "state", 1);
            //更新订单时间
            redisTemplate.opsForHash().delete(key, "updateTime");
            String time = nongsukeallidDao.getupdateTime(Long.valueOf(id));
            redisTemplate.opsForHash().put(key, "updateTime", time);
            return 1;
        }
        return 0;
    }

    /**
     * 获取用户创建的所有订单数据
     *
     * @param userid
     * @return
     */
    @Override
    public List getOrderAllToUser(int userid) {
        //返回结果集合
        List result = new ArrayList();
        //获取所有订单数据
        Set buyorderId = redisTemplate.boundSetOps(userid+":buynongsukegoods").members();
        List ids = new ArrayList<>(buyorderId);
        //获取订单数据返回
        for (int i = 0; i < ids.size(); i++) {
            Map entries = redisTemplate.opsForHash().entries("nongsukeall:" + ids.get(i));
            //对订单号处理成字符串，防止前端精度丢失
            Object id = entries.get("id");
            entries.put("id", "" + id);
            result.add(entries);
        }
        return result;
    }



    /**
     * 用户退款
     *
     * @param orderid
     * @return
     */
    @Override
    public int updateOrderRefund(String orderid) {
        int i = nongsukeallidDao.refundState(orderid);
        if(i == 1){
            //处理缓存
            String key = "nongsukeall:" + orderid;
            //修改订单hash表state状态
            redisTemplate.opsForHash().put(key, "state", 5);
            String time = nongsukeallidDao.getupdateTime(Long.valueOf(orderid));
            redisTemplate.opsForHash().put(key, "updateTime", time);
            return 1;
        }
        return 0;
    }

    /**
     * 获取单个订单数据
     *
     * @param orderid
     * @return
     */
    @Override
    public Nongsukeallid getNongsukeallidByOne(Long orderid) {
        Nongsukeallid nongsukeallid = nongsukeallidDao.selectOrder(orderid);
        return nongsukeallid;
    }

    /**
     * 购买用户确认完成订单
     * @param orderid
     * @return
     */
    @Override
    public int issueOverOrder(String orderid, int userid) throws IOException, IllegalAccessException {
        //获取订单信息
        Nongsukeallid order = nongsukeallidDao.selectOrder(Long.valueOf(orderid));
        if(order.getState() != 1 ){
            return  2;
        }
        //获取付款用户信息
        User user = userDao.selectUserAllById(order.getIssueid());
        if(user == null){
            return 2;
        }
        int i = nongsukeallidDao.issueaccomplishOrder(orderid);
        // 修改对应用户的金额
        //手续费
        BigDecimal rate = new BigDecimal(""+0.06);
        //订单价格
        BigDecimal money = new BigDecimal(""+order.getPrice());
        //卖家的收入
        BigDecimal income = money.subtract(money.multiply(rate));
        //结果保留2位小数，4舍，5入
        double requestMoney = income.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

        //获取内容订单发发布用户id集合
        ArrayList<NongsukeOrder> jsonContents = new ArrayList<>();
        JSONArray orders = JSON.parseArray(order.getOrderlist());
        for (Object jsonObject : orders) {
            NongsukeOrder jsonContent = JSONObject.parseObject(jsonObject.toString(), NongsukeOrder.class);
            jsonContents.add(jsonContent);
        }
        //获取发布人id
        String strid = "";
        for (NongsukeOrder o : jsonContents) {
             strid += o.getIssuseuserid()+",";
             System.out.println(strid);
        }
        String[] useridmoneyarr = strid.split(",");
        for(int j = 0; j < useridmoneyarr.length; j++) {
            //获取发布用户的money
            double userMoney = userDao.getUserMoney(Integer.parseInt(useridmoneyarr[j]));
            //对精度处理
            BigDecimal p1 = new BigDecimal(Double.toString(requestMoney));
            BigDecimal p2 = new BigDecimal(Double.toString(userMoney));
            //总价
            BigDecimal tataleMoney = p1.add(p2);
            //更新发布用户金额
            int i1 = userDao.updateUserMoney(tataleMoney, Integer.parseInt(useridmoneyarr[j]));
            //创建交易明细表
            MoneyInfo moneyInfo = new MoneyInfo();
            moneyInfo.setMoney(requestMoney);
            moneyInfo.setIssueuser(order.getIssueid());
            moneyInfo.setContinueuser(Integer.parseInt(useridmoneyarr[j]));
            moneyInfo.setGetmoenyorderid(order.getId());
            int i2 = moneyDao.addMoneyInfo(moneyInfo);
            if(i == 1 & i1 == 1 & i2 == 1){
                //修改缓存中的订单状态
                String key = "nongsukeall:" + orderid;
                //修改订单hash表state状态
                redisTemplate.opsForHash().put(key, "state", 3);
                String time = nongsukeallidDao.getupdateTime(Long.valueOf(orderid));
                redisTemplate.opsForHash().put(key, "updateTime", time);
                //设置消息内容
                String msg = "用户:"+user.getName() +"确认完成了订单标题为:"+order.getTitle()+"的订单,金额为："+ requestMoney +"元已到账！";
                int T = ChatEndpoint.orderMessage(String.valueOf(useridmoneyarr[j]),user.getName(),msg);
                if(T == 1){
                    return 1;
                }
                return 0;
            }
        }
        return 0;
    }
}
